package com.zlp.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author: zhulaiping
 * @time: 2022/8/29 13:36
 */
public class NettyHelloServer {


    public static void main(String[] args) {
        //1.启动器，负责装配netty组件，启动服务器
        new ServerBootstrap()
                //2.创建NioEventLoopGroup,可以理解为   线程 + selector
                .group(new NioEventLoopGroup())  //监听accept事件
                //3.选择服务器的ServerSocketChannel实现 OIO  NIO
                .channel(NioServerSocketChannel.class)
                //4. boss 负责处理连接，worker(child)负责处理读写，决定了worker(child)能执行那些操作
                .childHandler(
                        //5.channel代表和客户端进行数据读写的通道，Initializer 初始化，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //6.添加具体的handler
                        nioSocketChannel.pipeline().addLast(new StringDecoder()); //功能handler 将buf 转换为字符串
                        nioSocketChannel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {//自定义handler
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
                                System.out.println(s);
                            }
                        });
                    }
                }).bind(8080);

    }
}
